package com.example.yudong;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.mob.MobSDK;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //获取手机短信验证码
    private TimerTask tt;
    private Timer tm;
    private EditText yzmsjh; //输入手机号码框
    private EditText edit_code; //输入验证码框
    private Button btn_hqyzm; //获取短信验证码按钮
    private Button btn_hqyzmdl; //登录按钮
    private int TIME = 90; //倒计时60s这里应该多设置些因为mob后台需要60s,我们前端会有差异的建议设置90，100或者120
    private String country = "86"; //这是中国区号，如果需要其他国家列表，可以使用getSupportedCountries();获得国家区号
    private String phone;
    private static final int CODE_REPEAT = 1; //重新发送

    //清除验证码登录码界面手机号码框
    private EditText mPswTv;
    private ImageView pwdClean;

    //清除账号密码登录界面手机号码框
    private EditText mPswtv1;
    private ImageView pwdClean1;

    //明文密文
    private EditText et_psw; //密码框明文密文设置
    private boolean isHideFirst = true; //密码输入框密码是否是隐藏的，默认为true
    private ImageView imageView; //睁眼闭眼图标设置

    //按钮控制两个LinearLayout显示与隐藏
    private LinearLayout zhmmdl,yzmdl; //账号密码登录界面和验证码登录界面
    private Button btn_yzmdl,btn_mmdl; //两个界面的按钮

    //再按一次退出程序吐司
    private long lastBack = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //实现获取手机验证码功能（开始）
        MobSDK.init(this,"3175875f69897","a462ac2148daa622ff50fcbd40838211");
        SMSSDK.registerEventHandler(eh); ////注册短信回调（记得销毁，避免泄露内存）
        initView();

        //清除账号密码登录界面手机号码框（开始）
        mPswtv1 = (EditText)findViewById(R.id.zhmmsjh);
        //清除EditText输入的图标
        pwdClean1 = (ImageView)findViewById(R.id.iv_pwd_clear1);
        pwdClean1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPswtv1.setText(null);
            }
        });
        mPswtv1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    pwdClean1.setVisibility(View.VISIBLE);
                }else {
                    pwdClean1.setVisibility(View.GONE);
                }
            }
        });
        //清除账号密码登录界面手机号码框（结束）

        //清除获取手机验证码界面手机号码框（开始）
        mPswTv = (EditText)findViewById(R.id.yzmsjh);
        //清除EditText输入的图标
        pwdClean = (ImageView)findViewById(R.id.iv_pwd_clear);
        pwdClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPswTv.setText(null);
            }
        });
        mPswTv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    pwdClean.setVisibility(View.VISIBLE);
                }else {
                    pwdClean.setVisibility(View.GONE);
                }
            }
        });
        //清除获取手机验证码界面手机号码框（结束）

        //登录界面密码框明文密文（开始）
        et_psw = (EditText)findViewById(R.id.et_psw);
        imageView = (ImageView)findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.biyan);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.imageView:
                        if (isHideFirst == true){
                            imageView.setImageResource(R.drawable.zhengyan);
                            //密文
                            HideReturnsTransformationMethod method = HideReturnsTransformationMethod.getInstance();
                            et_psw.setTransformationMethod(method);
                            isHideFirst = false;
                        }else {
                            imageView.setImageResource(R.drawable.biyan);
                            //密文
                            TransformationMethod method = PasswordTransformationMethod.getInstance();
                            et_psw.setTransformationMethod(method);
                            isHideFirst = true;
                        }
                        //光标位置
                        int index = et_psw.getText().toString().length();
                        et_psw.setSelection(index);
                        break;
                }
            }
        });
        et_psw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    imageView.setVisibility(View.VISIBLE);
                }else {
                    imageView.setVisibility(View.GONE);
                }
            }
        });
        //登录界面密码框明文密文（结束）

        //控制两个LinearLayout显示与隐藏（开始）
        zhmmdl = (LinearLayout)findViewById(R.id.zhmmdl);
        yzmdl = (LinearLayout)findViewById(R.id.yzmdl);
        btn_mmdl = (Button)findViewById(R.id.btn_mmdl);
        btn_yzmdl = (Button)findViewById(R.id.btn_yzmdl);

        btn_mmdl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (zhmmdl.getVisibility() == View.INVISIBLE || yzmdl.getVisibility() == View.INVISIBLE){
                    zhmmdl.setVisibility(View.VISIBLE);
                }
                if (yzmdl.getVisibility() == View.VISIBLE || zhmmdl.getVisibility() == View.VISIBLE){
                    yzmdl.setVisibility(View.INVISIBLE);
                }
            }
        });

        btn_yzmdl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (yzmdl.getVisibility() == View.INVISIBLE || zhmmdl.getVisibility() == View.INVISIBLE){
                    yzmdl.setVisibility(View.VISIBLE);
                }
                if (zhmmdl.getVisibility() == View.VISIBLE || yzmdl.getVisibility() == View.VISIBLE){
                    zhmmdl.setVisibility(View.INVISIBLE);
                }
            }
        });
        //控制两个LinearLayout显示与隐藏（结束）
    }

    public void onBackPressed() {
        if (lastBack == 0 || System.currentTimeMillis() - lastBack > 2000){
            Toast.makeText(MainActivity.this,"再按一次退出程序",Toast.LENGTH_LONG).show();
            lastBack = System.currentTimeMillis();
            return;
        }
        super.onBackPressed();
    }

    //实现获取手机验证码功能（开始）
    Handler hd = new Handler(){
        @Override
        public void handleMessage (Message msg){
            if (msg.what == CODE_REPEAT){
                btn_hqyzm.setEnabled(true);
                btn_hqyzmdl.setEnabled(true);
                tm.cancel(); //取消任务
                tt.cancel(); //取消任务
                TIME = 90; //时间重置
                btn_hqyzm.setText("重新发送验证码");
            }else {
                btn_hqyzm.setText(TIME+"秒后重新发送");
            }
        }
    };

    //回调
    EventHandler eh = new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data){
            if (result == SMSSDK.RESULT_COMPLETE){
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){
                    toast("验证成功");
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this,HomePage.class);
                    startActivity(intent);
                    finish();
                }else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){ //获取验证码成功
                    toast("获取验证码成功");
                }else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){ //如果你调用了获取国家区号类表会在这里回调
                    //返回支持发送验证码的国家列表
                }
            }else { //错误等在这里（包括验证失败）
                //错误码请参照http://wiki.mob.com/android-api-错误码参考/这里我就不再继续写了
                ((Throwable)data).printStackTrace();
                String str = data.toString();
                toast(str);
            }
        }
    };

    //toast的一个小方法
    private void toast(final String str){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initView() {
        yzmsjh = (EditText)findViewById(R.id.yzmsjh);
        edit_code = (EditText)findViewById(R.id.edit_code);
        btn_hqyzm = (Button)findViewById(R.id.btn_hqyzm);
        btn_hqyzmdl = (Button)findViewById(R.id.btn_hqyzmdl);
        btn_hqyzm.setOnClickListener(this);
        btn_hqyzmdl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_hqyzm:
                phone = yzmsjh.getText().toString().trim().replaceAll("/s","");
                if (!TextUtils.isEmpty(phone)){
                    //定义需要匹配的正则表达式的规则
                    String REGEX_MOBILE_SIMPLE = "[1][3456789]\\d{9}";
                    Pattern pattern = Pattern.compile(REGEX_MOBILE_SIMPLE);
                    //把需要匹配的字符给模板匹配，获得匹配器
                    Matcher matcher = pattern.matcher(phone);
                    // 通过匹配器查找是否有该字符，不可重复调用重复调用matcher.find()
                    if (matcher.find()){//匹配手机号是否存在
                        alterWarning();
                    }else {
                        toast("请输入正确的手机号");
                    }
                }else {
                    toast("请先输入手机号");
                }
                break;

            case R.id.btn_hqyzmdl:
                //获得用户输入的验证码
                String code = edit_code.getText().toString().replaceAll("/s","");
                if (!TextUtils.isEmpty(code)){//判断验证码是否为空
                    //验证
                    SMSSDK.submitVerificationCode(country,phone,code);
                }else {//如果用户输入的内容为空，提醒用户
                    toast("请输入验证码后再提交");
                }
                break;
            default:
        }
    }

    //弹窗确认下发送
    private void alterWarning () {
        //构造器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示"); //设置标题
        builder.setMessage("我们将要发送到" + phone + "验证"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher); //设置图标,图片id即可
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
                //通过sdk发送短信验证（请求获取短信验证码，在监听（eh）中返回）
                SMSSDK.getVerificationCode(country, phone);
                //做倒计时操作
                Toast.makeText(MainActivity.this, "已发送" + which, Toast.LENGTH_LONG).show();
                btn_hqyzm.setEnabled(false);
                btn_hqyzmdl.setEnabled(true);
                tm = new Timer();
                tt = new TimerTask() {
                    @Override
                    public void run() {
                        hd.sendEmptyMessage(TIME--);
                    }
                };
                tm.schedule(tt,0,1000);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Toast.makeText(MainActivity.this,"已取消" + which,Toast.LENGTH_LONG).show();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    //销毁短信注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销回调接口registerEventHandler必须和unregisterEventHandler配套使用，否则可能造成内存泄漏。
        SMSSDK.unregisterEventHandler(eh);
    }
    //实现获取手机验证码功能（结束）
}